<template>
  <div>
    <el-form :inline="true" class="demo-form-inline" :model="formSelect">
      <!-- Form -->
      <el-button
        type="primary"
        @click="dialogFormVisible = true"
        style="margin-right: 10px"
        >新增</el-button
      >
      <el-dialog title="新增用户信息" :visible.sync="dialogFormVisible">
        <!-- model绑定表单和每行内容item -->
        <el-form :model="form" :rules="rules" ref="form">
          <!-- :rules="rules" 表单验证设置 prop="username" 表单验证属性 -->
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              v-model="form.username"
              autocomplete="off"
              placeholder="请输入用户名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            :label-width="formLabelWidth"
            prop="password"
          >
            <el-input
              v-model="form.password"
              autocomplete="off"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号码"
            :label-width="formLabelWidth"
            prop="telephone"
          >
            <el-input
              v-model="form.telephone"
              autocomplete="off"
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input
              v-model="form.email"
              autocomplete="off"
              placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="注册身份"
            :label-width="formLabelWidth"
            prop="privilege"
          >
            <el-select v-model="form.privilege" placeholder="请选择注册身份">
              <el-option label="普通用户" value="0"></el-option>
              <el-option label="管理员" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="头像"
            :label-width="formLabelWidth"
            placeholder="请上传头像"
          >
            <el-upload
              class="avatar-uploader"
              action="/api/users/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="changeClose">取 消</el-button>
          <el-button
            type="primary"
            @click="(dialogFormVisible = false), changeUsers(form)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-form-item label="">
        <el-select v-model="formSelect.type" placeholder="请选择查询类型">
          <el-option label="全部" value="all"></el-option>
          <el-option label="用户名称" value="username"></el-option>
          <el-option label="用户密码" value="password"></el-option>
          <el-option label="手机号码" value="telephone"></el-option>
          <el-option label="邮箱" value="email"></el-option>
        </el-select>
      </el-form-item>
      <el-input
        placeholder="请输入内容"
        v-model="formSelect.value"
        clearable
        @change="chooseValue(formSelect.value)"
        style="width: 200px; margin-right: 10px; height: 41px"
      >
      </el-input>
      <el-form-item>
        <el-button type="primary" @click="onSerch">查询</el-button>
      </el-form-item>
    </el-form>
    <div>
      <span v-if="isLoading">正在登录...</span>
       <el-table :data="users" border style="width: 100%">
      <el-table-column prop="picture" label="用户头像">
        <template slot-scope="scope">
          <el-image
            style="widt: 100px; height: 50px"
            :src="'/api/images/' + scope.row.picture"
            fit=""
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名称"> </el-table-column>
      <el-table-column prop="password" label="用户密码"> </el-table-column>
      <el-table-column prop="telephone" label="手机号码"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="privilege" label="身份管理">
        <!-- 通过 Scoped slot 可以获取到每行里面的数据 -->
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ scope.row.privilege == 0 ? "普通用户" : "管理员" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="
              (deleteFormVisible = true), handleEdit(scope.$index, scope.row)
            "
            >编辑</el-button
          >
          <el-dialog
            title="修改用户信息"
            :visible.sync="deleteFormVisible"
            :before-close="formClose"
          >
            <!-- model绑定表单和每行内容item -->
            <el-form :model="amendForm" ref="amendForm">
              <!-- :rules="rules" 表单验证设置 prop="username" 表单验证属性 -->
              <el-form-item
                label="用户名"
                :label-width="formLabelWidth"
                prop="username"
              >
                <el-input
                  v-model="amendForm.username"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="密码"
                :label-width="formLabelWidth"
                prop="password"
              >
                <el-input
                  v-model="amendForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="手机号码"
                :label-width="formLabelWidth"
                prop="telephone"
              >
                <el-input
                  v-model="amendForm.telephone"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="邮箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  v-model="amendForm.email"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="注册身份"
                :label-width="formLabelWidth"
                prop="privilege"
              >
                <el-select v-model="amendForm.privilege">
                  <el-option label="普通用户" value="0"></el-option>
                  <el-option label="管理员" value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="头像"
                :label-width="formLabelWidth"
                placeholder="请上传头像"
              >
                <el-upload
                  class="avatar-uploader"
                  action="/api/users/upload"
                  :show-file-list="false"
                  :on-success="imgSuccess"
                >
                  <img v-if="imageUrls" :src="imageUrls" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="buttonClose">取 消</el-button>
              <el-button type="primary" @click="buttonUsers(amendForm)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    </div>
   
    <PagerComp
      :pageSize="pageSize"
      :page="page"
      :pagerCount="pagerCount"
      :total="total"
      @pageChange="CurrentChange"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";
import PagerComp from "./PagerComp";
export default {
  data() {
    return {
      //分页
      page: 1,
      pageSize: 5, //每页显示条数
      pagerCount: 7, //奇数
      //上传图片
      imageUrl: "",
      imageUrls: "",
      //模糊查询数组
      arr: [],
      //搜索下拉框
      formSelect: {
        type: " ",
        value: "",
      },
      form: {
        username: "",
        password: "",
        telephone: "",
        email: "",
        picture: "",
        privilege: "",
        createTime: "",
      },
      amendForm: {
        _id: "",
        username: "",
        password: "",
        telephone: "",
        email: "",
        picture: "",
        privilege: "",
        createTime: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        privilege: [
          { required: true, message: "请选择注册身份", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "请选择注册日期", trigger: "blur" },
        ],
      },
      dialogFormVisible: false, //判断弹出层是否显示的布尔值 false为关闭
      deleteFormVisible: false,
      formLabelWidth: "120px",
    };
  },
  methods: {
    //分页
    CurrentChange(page) {
      this.page = page;
      this.$store.dispatch("userStore/getAllUsers", {
        page,
        pageSize: this.pageSize,
      });
    },
    //上传图片
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(URL.createObjectURL(file.raw));
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.picture = res.data;
    },
     //编辑图片
    imgSuccess(res, file) {
      console.log(res);
      console.log(URL.createObjectURL(file.raw));
      this.imageUrls = URL.createObjectURL(file.raw);
      this.form.picture = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //编辑 信息回填
    handleEdit(index, row) {
      this.amendForm = {
        _id: row._id,
        username: row.username,
        password: row.password,
        telephone: row.telephone,
        email: row.email,
        picture: row.picture,
        privilege: row.privilege == 0 ? "普通用户" : "管理员", //通过三目判断用户
      };
    },
    handleDelete(index, row) {
      //删除
      this.$store.dispatch("userStore/deleteOne", row._id); //row是个对象，能得到每行表格里面的内容 row._id里面的属性
      this.$store.dispatch("userStore/getAllUsers"); //删除一个以后 重新渲染页面表格
    },
    //新增
    changeUsers(form) {
      //验证表单是否符合规则
      console.log("数据", this.form);
      this.$refs.form.validate((valid) => {
        console.log("valid", valid);
        if (valid) {
          //没有创建空对象时 可以进行后续对数据的处理
          //通过 model绑定表单 名字是form
          //新增 传形参
          this.$store.dispatch("userStore/getUsers", form);
          // console.log("对象", form);
          //清空表单输入内容 关闭弹窗
          this.handleClose();
          this.$store.dispatch("userStore/getAllUsers"); //新增一个以后 重新渲染页面表格
        }
      });
    },
    //弹窗关闭清空输入的值
    //before-close 仅当用户通过点击关闭图标或遮罩关闭 Dialog 时起效。 :before-close="handleClose"
    //resetFields	对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
    handleClose() {
      //ref 绑定控件，$refs 获取控件 获取到表单的内容并进行清空
      // console.log("this.$refs.form", this.$refs.form);
      this.$refs.form.resetFields();
      //关闭弹窗
      this.dialogFormVisible = false;
    },
    changeClose() {
      //清空表单输入内容 关闭弹窗
      this.handleClose();
    },
    formClose() {
      // console.log("this.$refs.amendForm", this.$refs.amendForm);
      this.$refs.amendForm.resetFields();
      //关闭弹窗
      this.deleteFormVisible = false;
    },
    //修改取消按钮
    buttonClose() {
      //清空表单输入内容 关闭弹窗
      this.formClose();
    },
    //确定修改按钮
    buttonUsers(user) {
      //修改 传形参
      // user.privilege = this.amendForm.privilege;
      this.$store.dispatch("userStore/changeOne", user);
      //清空表单输入内容 关闭弹窗
      this.formClose();
      this.$store.dispatch("userStore/getAllUsers"); //修改一个以后 重新渲染页面表格
    },
    //模糊查询
    onSerch() {
      console.log("this.formSelect", this.formSelect);
      this.$store.dispatch("userStore/getOneUser", this.formSelect);
    },
    chooseValue(value) {
      if (value !== "") {
        // console.log("value",value);
        let resp = this.arr.filter(
          (item) =>
            !value ||
            item.username.toLowerCase().includes(value.toLowerCase()) ||
            item.password.toLowerCase().includes(value.toLowerCase()) ||
            item.email.toLowerCase().includes(value.toLowerCase()) ||
            item.telephone
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase())
        );
        console.log("onSerch", resp);
        this.$store.commit("userStore/setUsers", resp); //找到了显示查询数组
        this.$store.state.total = resp.length;
        this.$store.commit("userStore/setTotal", this.$store.state.total); //找到了更新总条数
        console.log("total", this.$store.state.total);
      } else {
        this.$store.dispatch("userStore/getAllUsers"); //否则显示所有
      }
    },
  },
  computed: {
    //计算属性
    ...mapState("userStore", ["isLoading", "users", "total"]),
  },
  components: {
    PagerComp,
  },
  created() {
    //一开始就显示读取异步的数据
    this.$store.dispatch("userStore/getAllUsers").then((resp) => {
      // console.log("用户", resp);
      this.arr = resp.rows;
      console.log("用户", this.arr);
    });
    console.log("111", this.$store.state);
  },
};
</script>

<style scoped>
.demo-form-inline {
  margin-top: 20px;
  text-align: left !important;
}
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
  border: 1px dashed #d9d9d9 !important;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>